var express = require('express');
var router = express.Router();
var qiniu = require('qiniu');
var rpcFunc=require('../routes/rpcSrv/rpcFunc.js');
var superagent = require('superagent');

var ItbUserModel = require('../../common/mysql/mapping/ItbUserModel');
var TgMapDocModel = require('../../common/mysql/mapping/TgMapDocModel');
var TgMapPageModel = require('../../common/mysql/mapping/TgMapPageModel');
var TgMapPcModel = require('../../common/mysql/mapping/TgMapPcModel');
var TgDesignDocModel = require('../../common/mysql/mapping/TgDesignDocModel');
var TgDesignPageModel = require('../../common/mysql/mapping/TgDesignPageModel');
var TgDesignPcModel = require('../../common/mysql/mapping/TgDesignPcModel');
var VideoDesignDocModel = require('../../common/mysql/mapping/VideoDesignDocModel');
var YjxCustAnimationModel = require('../../common/yjxMysql/mapping/YjxCustAnimationModel');
var YjxUniItemsModel = require('../../common/yjxMysql/mapping/YjxUniItemsModel');
var ItbImageModel = require('../../common/mysql/mapping/ItbImageModel');
var ItbGraphModel = require('../../common/mysql/mapping/ItbGraphModel');
var ItbMediaModel = require('../../common/mysql/mapping/ItbMediaModel');
var OSSMgr = require('../../common/util/OSSMgr');
var CONFIG = require('../../common/config');
var CODE = require('../../common/code');

var async = require( 'async'); // 同步控制

var moment = require('moment');  // 日期格式化

var BASE_IP = CONFIG.BASE_IP;

var documentUtil = require('../yjx/v1/util/documentUtil');
var retUtil = require('../yjx/v1/util/retUtil');


//------------------------------------------------------------------
/* 获取分页映射信息(设计编辑器加载用 新建设计时)
 * 方式:GET/POST
 * 参数 device:
 * 参数 uuid: 设备标识
 * 参数 mId: 分页模版文档id
 * 返回数据:
 * {
 *      "name": "文档名",
 *      "docData": "{SJGTG结构Json字符串}",
 *      "pagesData":[
 *          {
 *              "data": "{page data json string}",
 *              "page_id": "15",
 *              "page_index": "0",
 *              "pcData": [
 *                  {
 *                      "data": "{page content data json string}",
 *                      "pc_id": "17",
 *                      "pc_index": "0",
 *                  },
 *                  ...
 *              ]
 *          },
 *          ...
 *      ]
 * }
 *
 * */
function getMappingInfo(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var mapId = Number(req.body.mId || req.query.mId || '0');

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // CHECK
    if (typeof mapId=='undefined' || isNaN(mapId) || mapId==null || mapId==0) {
        return ret_func(0, "无效参数");
    }

    // 获取文档
    var docEnt = new TgMapDocModel({
        map_id: mapId,
    });
    docEnt.getMapDocInfoById(function (err, docRets) {
        if (err) {
            console.log('design.js [getMappingInfo] getDoc Err: ' + err);
            return ret_func(0, CODE.OPERATION_FAILED);
        }

        // 返回值
        var retData = {
            name: '',
            ver:1,// 201610311205 version of data
            pagesData: []
        };

        if(docRets && docRets.length>0) {
            var dbDoc = docRets[0];
            retData.name = dbDoc.map_name||'';//set return name
            retData.docData = dbDoc.data||'';// set return doc data
            retData.ver = dbDoc.ver ||1; // set return version data // 201610311205 version of data

            var pcEnt = new TgMapPcModel({
                map_id: mapId,
            });
            pcEnt.getMapPageAndPcInfo(function(err2, pageRets) {
                if(err2){
                    console.log('design.js [getMappingInfo] getPagePc Err: ' + err2);
                    return ret_func(0, CODE.OPERATION_FAILED);
                }

                if(pageRets && pageRets.length>0) {// 返回值以page为单位
                    retData.pagesData = pageRets||[];//set return pages data
                }

                return ret_func(1,CODE.OPERATION_SUCCESS, retData);
            });

        } else {
            return ret_func(1,CODE.OPERATION_SUCCESS, null);
        }
    });

}
router.get('/getMappingInfo', getMappingInfo);
router.post('/getMappingInfo', getMappingInfo);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取设计模版信息(设计编辑器加载用 编辑设计时)
 * 方式:GET/POST
 * 参数 device:
 * 参数 uuid: 设备标识
 * 参数 dId: 设计文档id
 * 返回数据:
 * {
 *      "name": "文档名",
 *      "docData": "{SJGTG结构Json字符串}",
 *      "pagesData":[
 *          {
 *              "data": "{page data json string}",
 *              "page_id": "15",
 *              "page_index": "0",
 *              "pcData": [
 *                  {
 *                      "data": "{page content data json string}",
 *                      "pc_id": "17",
 *                      "pc_index": "0",
 *                  },
 *                  ...
 *              ]
 *          },
 *          ...
 *      ]
 * }
 *
 * */
function getDesignInfo(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var designId = Number(req.body.dId || req.query.dId || '0');

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // CHECK
    if (typeof designId=='undefined' || isNaN(designId) || designId==null || designId==0) {
        return ret_func(0, "无效参数");
    }

    // 获取文档
    var docEnt = new TgDesignDocModel({
        design_id: designId,
    });
    docEnt.getDocInfoById(function (err, docRets) {
        if (err) {
            console.log('design.js [getDesignInfo] getDoc Err: ' + err);
            return ret_func(0, CODE.OPERATION_FAILED);
        }

        // 返回值
        var retData = {
            name: '',
            ver:1,// 201610311205 version of data
            pagesData: []
        };

        if(docRets && docRets.length>0) {
            var dbDoc = docRets[0];
            retData.name = dbDoc.design_name||'';//set return name
            retData.docData = dbDoc.data||'';// set return doc data
            retData.ver = dbDoc.ver||1;// set return version // 201610311205 version of data
            retData.videoSizeId = Number(dbDoc.video_size_id||'0')||0;
            retData.videoPos = dbDoc.video_pos||'';// 2017-12-13 FOR 视频背景模版

            var pcEnt = new TgDesignPcModel({
                design_id: designId,
            });
            pcEnt.getPageAndPcInfo(function(err2, pageRets) {
                if(err2){
                    console.log('design.js [getDesignInfo] getPagePc Err: ' + err2);
                    return ret_func(0, CODE.OPERATION_FAILED);
                }

                if(pageRets && pageRets.length>0) {// 返回值以page为单位
                    retData.pagesData = pageRets||[];//set return pages data
                }

                return ret_func(1,CODE.OPERATION_SUCCESS, retData);
            });

        } else {
            return ret_func(1,CODE.OPERATION_SUCCESS, null);
        }
    });

}
router.get('/getDesignInfo', getDesignInfo);
router.post('/getDesignInfo', getDesignInfo);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 保存设计文档信息(设计编辑器用)
 * 方式:GET/POST
 * 参数 device:
 * 参数 uuid: 设备标识
 * 参数 uId: 用户id
 * 参数 mId: MapId
 * 参数 dId: 设计文档id
 * 参数 editData: 编辑器文档数据(Json字符串): {name:'xxx', eigenValue:'[1,2,3]', docData:'yyy', pagesData:'zzz', ver:1}
 * 返回数据:
 * {
 *      "designId": 1,
 *      "pageIds":[
 *          {
 *              "pageId": 10,
 *              "pcIds": [111, 112, ...]
 *          },
 *          ...
 *      ]
 * }
 * */
function saveDesignInfo(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var userId = Number(req.body.uId || req.query.uId || '0');
    var mapId = Number(req.body.mId || req.query.mId || '0');
    var designId = Number(req.body.dId || req.query.dId || '0');
    var editDataStr = req.body.editData || req.query.editData || '{}';
    var editData = JSON.parse(editDataStr);
    var vPos = req.body.vPos || req.query.vPos || '';
    var vSizeId = Number(req.body.vSizeId || req.query.vSizeId || '0');

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // 参数检查
    var newFlg = true;
    if (typeof mapId=='undefined' || isNaN(mapId) || mapId==null || mapId==0) {
        if (typeof designId=='undefined' || isNaN(designId) || designId==null || designId==0) {
            return ret_func(0, "无效参数");
        }
        var newFlg = false;
    }
    if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
        return ret_func(0, "未知用户");
    }

    // 检索user
    var userEnt = new ItbUserModel({
        user_id : userId,
        del_flg : 0
    });
    userEnt.findFromDB(function(chkErr, userChkRet){
        if (chkErr){
            console.log('design.js [saveDesignInfo] Check User Err: '+chkErr);
            return ret_func(0,CODE.OPERATION_FAILED);
        }

        // 合法用户
        if(userChkRet && userChkRet.length>0) {
            // 处理
            if (newFlg) {// 新规
                // 取map数据
                var mapEntity = new TgMapDocModel({
                    map_id:mapId,
                    del_flg:0
                });
                mapEntity.findFromDB(function(findErr, findRet){
                    if (findErr){
                        console.log('design.js [saveDesignInfo] Find MapDoc Err: '+findErr);
                        return ret_func(0,CODE.OPERATION_FAILED);
                    }

                    if (findRet != null && findRet.length > 0) {
                        var mapInfo = findRet[0];

                        // 新建doc
                        var newDocEntity = new TgDesignDocModel({
                            from_design_id: null,// TODO
                            tg_id: mapInfo.tg_id,
                            map_id: mapInfo.map_id,
                            design_name: editData.name || '设计模版',
                            user_id: userId,
                            user_type: 1,
                            publish: 0,
                            data: editData.docData||mapInfo.data,// TODO
                            hash_tag: editData.eigenValue || '[]',
                            size_id: mapInfo.size_id,
                            type_id: mapInfo.type_id,
                            video_size_id: vSizeId,
                            video_pos: vPos,
                            order: 999,// TODO
                            ver: editData.ver || 1,
                            update_by: userId,
                        });
                        // insert document
                        newDocEntity.saveToDB(function(saveErr, newDocId){
                            if (saveErr) {
                                console.log('design.js [saveDesignInfo] Insert Doc Err: '+saveErr);
                                return ret_func(0,CODE.OPERATION_FAILED);
                            }

                            // 新建pages
                            var pageEntity = new TgDesignPageModel({
                                design_id: newDocId,
                                user_id: userId
                            });
                            pageEntity.updatePages(function(err,result){
                                if (err) {
                                    console.log('design.js [saveDesignInfo] Insert Pages Err: '+err);
                                    return ret_func(0,CODE.OPERATION_FAILED);
                                }

                                var retData = {
                                    designId: newDocId,
                                    pageIds: result || []// 已按page_index排序
                                };

                                return ret_func(1,CODE.OPERATION_SUCCESS,retData);

                            }, editData.pagesData, true);// create new
                        });


                    } else {
                        console.log('design.js [saveDesignInfo] MapDoc Not Exist ');
                        return ret_func(0, "未找到分页模版");
                    }
                });

            } else {// 更新
                // 先检查设计模版
                var chkEnt = new TgDesignDocModel({
                    design_id: designId,
                    del_flg: 0,
                });
                chkEnt.findFromDB(function(chkErr, chkRet){
                    if (chkErr) {
                        console.log('design.js [saveDesignInfo] Find Doc Err: '+chkErr);
                        return ret_func(0,CODE.OPERATION_FAILED);
                    }

                    if(chkRet && chkRet.length>0) {

                        //判断用户角色
                        var opt = {
                            queryType : 2,
                            userId : userId
                        };
                        (new ItbUserModel()).getBackUserInfo(opt, function (error, userInfo) {
                            if(error || !userInfo || userInfo.length <=0) {
                                return ret_func(0, error || '该用户不存在或权限不足');
                            }

                            if(Number(chkRet[0].publish || '0') == 1) {
                                return ret_func(0,"不能修改已发布的设计模版");
                            }

                            //我们的设计师
                            if(userInfo.itbourBackInfo){
                                //todo
                            }else if(userInfo.yjscDesignPlatformInfo){
                                // 用户角色(多角色用户按位与): 0普通用户, 1一级管理员, 2二级管理员, 4三级管理员, 8超级管理员, 16设计人员, 32模版操作员, 64印刷对接员, 128客服 , 256测试员, 512市场人员, 1024环信客服
                                // 管理员+设计人员 1+2+4+8+16 = 31
                                //后台操作人员直接可修改
                                if((userInfo.yjscDesignPlatformInfo.role & 32) != 32){
                                    // 上架流程状态: 0未知;20提交上架申请待审核;31一级审核通过,32二级审核通过;41一级审核失败,42二级审核失败
                                    if([20,31].indexOf(chkRet[0].state)>=0){
                                        return ret_func(0,"不能修改已提交的设计模版");
                                    }else if(chkRet[0].state ==32){
                                        if(chkRet[0].state2 !=32){
                                            return ret_func(0,"不能修改已提交的设计模版");
                                        }
                                    }

                                    if(chkRet[0].user_id!=userId){
                                        return ret_func(0,"不能修改他人设计模版");
                                    }
                                }
                            }else{
                                return ret_func(0, '权限不足');
                            }



                            // 更新doc
                            var docEnt = new TgDesignDocModel({
                                design_id: designId,
                                design_name: editData.name || '',
                                data: editData.docData,// TODO
                                ver: editData.ver || 1,
                                finetune_data: '',// 清空微调数据
                                video_size_id: vSizeId,
                                video_pos: vPos,
                                update_by: userId,
                                hash_tag: editData.eigenValue || '[]',
                            });
                            docEnt.updateToDB(function(updErr, updRet){
                                if (updErr) {
                                    console.log('design.js [saveDesignInfo] Update Doc Err: '+updErr);
                                    return ret_func(0,CODE.OPERATION_FAILED);
                                }

                                // 更新pages
                                var pageEnt = new TgDesignPageModel({
                                    design_id: designId,
                                    user_id: userId
                                });
                                pageEnt.updatePages(function(updErr2, result){
                                    if (updErr2) {
                                        console.log('design.js [saveDesignInfo] Update Pages Err: '+updErr2);
                                        return ret_func(0,CODE.OPERATION_FAILED);
                                    }

                                    var retData = {
                                        designId: designId,
                                        userId:userId,
                                        pageIds: result || []// 已按page_index排序
                                    };

                                    return ret_func(1,CODE.OPERATION_SUCCESS,retData);

                                }, editData.pagesData, false);// update

                            });
                        });

                    } else {
                        return ret_func(0,"设计模版不存在");
                    }
                });
            }

        } else {
            return ret_func(0,"非法用户");
        }
    });

}
router.get('/saveDesignInfo', saveDesignInfo);
router.post('/saveDesignInfo', saveDesignInfo);

// 用户保存ai插件导出的设计文档
function saveNewDesignInfo2(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;
    var userId = Number(req.body.uId || req.query.uId || '0')||0;
    var mapId = Number(req.body.mId || req.query.mId || '0')||0;
    var editDataStr = req.body.editData || req.query.editData || '{}';
    var editData = JSON.parse(editDataStr);
    var vPos = req.body.vPos || req.query.vPos || '';
    var sizeId = Number(req.body.sizeId || req.query.sizeId || '0')||0;
    var typeId = Number(req.body.typeId || req.query.typeId || '0')||0;
    var vSizeId = Number(req.body.vSizeId || req.query.vSizeId || '0')||0;

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // 参数检查
    if(typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
        return ret_func(0, "未知User");
    }
    if(typeof sizeId=='undefined' || isNaN(sizeId) || sizeId==null || sizeId==0) {
        return ret_func(0, "未知Size");
    }
    if(typeof typeId=='undefined' || isNaN(typeId) || typeId==null || typeId==0) {
        return ret_func(0, "未知Type");
    }

    // 检索user
    var userEnt = new ItbUserModel({
        user_id : userId,
        del_flg : 0
    });
    userEnt.findFromDB(function(chkErr, chkRet){
        if (chkErr){
            console.log('design.js [saveNewDesignInfo2] Check User Err: '+chkErr);
            return ret_func(0,CODE.OPERATION_FAILED);
        }

        // 合法用户
        if(chkRet && chkRet.length>0) {
            // 新建doc
            var newDocEntity = new TgDesignDocModel({
                from_design_id: null,
                tg_id: 0,// TODO
                map_id: mapId,// TODO
                design_name: editData.name || '设计模版',
                user_id: userId,
                user_type: 1,
                publish: 0,
                data: editData.docData||'',
                hash_tag: editData.eigenValue || '[]',
                size_id: sizeId,
                type_id: typeId,
                video_size_id: vSizeId,
                video_pos: vPos,
                order: 999,// TODO
                ver: editData.ver || 1,
                update_by: userId,
            });
            // insert document
            newDocEntity.saveToDB(function(saveErr, newDocId){
                if (saveErr) {
                    console.log('design.js [saveNewDesignInfo2] Insert Doc Err: '+saveErr);
                    return ret_func(0,CODE.OPERATION_FAILED);
                }

                // 新建pages
                var pageEntity = new TgDesignPageModel({
                    design_id: newDocId,
                    user_id: userId
                });
                pageEntity.updatePages(function(err,result){
                    if (err) {
                        console.log('design.js [saveNewDesignInfo2] Insert Pages Err: '+err);
                        return ret_func(0,CODE.OPERATION_FAILED);
                    }

                    var retData = {
                        designId: newDocId,
                        userId:userId,
                        pageIds: result || []// 已按page_index排序
                    };

                    return ret_func(1,CODE.OPERATION_SUCCESS,retData);

                }, editData.pagesData, true);// create new
            });

        } else {
            return ret_func(0,"非法用户");
        }
    });

}
router.get('/saveNewDesignInfo2', saveNewDesignInfo2);
router.post('/saveNewDesignInfo2', saveNewDesignInfo2);

//------------------------------------------------------------------
/* 获取图片列表 (设计编辑器用 编辑)
 * 方式:GET/POST
 * 参数 device:
 * 参数 user_id: 用户id
 * 参数 pageNum: 分页号, 当前第几页，>=0
 * 参数 pageSize: 分页大小, 一页的数量
 * 参数[可选] key: 搜索关键字
 * 返回数据:
 * {
 *   "msg": "成功",
 *   "data": {
 *     "imageList":[{
 *       "img_id": 36,
 *       "img_name": "企业培训",
 *       "url":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U8/2016/04/12/111736242_9195288177579642/0.jpg",
 *       "create_time": "2016/04/01 12:11:17"
 *     }],
 *     "pageCount":32,
 *     "pageNum":0,
 *     "pageSize":9
 *   },
 *   "success": 1
 * }
 * 测试地址：http://127.0.0.1:3000/design/getImageList?user_id=13&pageNum=0&pageSize=3
 *          http://127.0.0.1:3000/design/getImageList?user_id=13&pageNum=0&pageSize=3&key=cb
 *
 * */
function getImageList(req, res, next) {
    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var key = req.query.key || req.body.key ||null;
    var pageNum = Number(req.query.pageNum || req.body.pageNum ||0);
    var pageSize = Number(req.query.pageSize || req.body.pageSize ||12);
    var skipCnt = pageNum*pageSize;

    var user_id = req.query.user_id || req.body.user_id ||0;
    if(!user_id){
        return ret_func(0,'fail! user_id is null!',null);
    }
    var entity = new ItbImageModel({
        user_id:user_id,
        del_flg:0
    });

    // 无关键字
    if(key==null){
        entity.findCountFromDB(function(error,pageCount){
            if(error){
                console.log(error);
                return ret_func(0,error,null);
            }
            entity.findImgByUser(function(error2,items){
                if(error2){
                    console.log(error2);
                    return ret_func(0,error2,null);
                }

                var data = {};
                data.pageCount = Math.ceil(Number(pageCount||'0')/pageSize);// 向上取整
                data.pageNum = pageNum;
                data.pageSize = pageSize;
                data.imageList = items;

                return ret_func(1,'success',data);
            },skipCnt,pageSize);
        });
    }else{
        // 有关键字
        entity.findCountFromDBWithKey(key, function(error,pageCount){
            if(error){
                console.log(error);
                return ret_func(0,error,null);
            }

            entity.findFromDBWithKey(key, function(error2,items){
                if(error2){
                    console.log(error2);
                    return ret_func(0,error2,null);
                }

                var data = {};
                data.pageCount = Math.ceil(Number(pageCount||'0')/pageSize);// 向上取整
                data.pageNum = pageNum;
                data.pageSize = pageSize;
                data.imageList = items;

                var retJson ={
                    success: 1,
                    msg: 'success',
                    data:data
                };

                return ret_func(1,'success',data);
            },skipCnt,pageSize);
        });
    }


}

router.get('/getImageList', getImageList);
router.post('/getImageList', getImageList);

//------------------------------------------------------------------
/* 删除图片 (设计编辑器用 编辑)
 * 方式:GET/POST
 * 参数 device:
 * 参数 user_id: 用户id
 * 参数 img_id: 图片id
 * 返回数据:
 * {
 *   "msg": "成功",
 *   "data": {},
 *   "success": 1
 * }
 * 测试地址：http://127.0.0.1:3000/design/deleteImage?img_id=12242&user_id=13
 *
 * */
function deleteImage(req, res, next) {
// return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var img_id = Number(req.query.img_id || req.body.img_id || '0');
    if(!img_id){
        return ret_func(0,'fail! img_id is null!',null);
    }
    var user_id = req.query.user_id || req.body.user_id || 0;
    if(!user_id){
        return ret_func(0,'fail! user_id is null!',null);
    }
    var entity = new ItbImageModel({
    });
    entity.logicDeleteImage(user_id, img_id, function(error){
        if(error){
            console.log(error);
            return ret_func(0,error,null);
        }
        return ret_func(1,'success',{});
    });

}

router.get('/deleteImage', deleteImage);
router.post('/deleteImage', deleteImage);

//------------------------------------------------------------------
/* 获取默认的图形列表  (设计编辑器用 编辑)
 * 方式:GET/POST
 * 参数 device:
 * 参数 user_id: 用户id
 * 参数 pageNum: 分页号, 当前第几页，>=0
 * 参数 pageSize: 分页大小, 一页的数量
 * 参数[可选] key: 搜索关键字
 * 参数[可选] type: 图形分类
 * 返回数据:
 * {
 *   "msg": "成功",
 *   "data": {
 *     "graphList":[
 *     {
 *       "graph_id": 36,
 *       "graph_type": 2,
 *       "graph_name": "企业培训",
 *       "data":"{\"paths\":[{\"points\":[[0,100,8],[0,0,1],[25.21,0,1],[25.21,100,1],[0,100,1],[0,100,9]],\"w\":0,\"h\":0},{\"points\":[[46.34,100,8],[46.34,0,1],[71.56,0,1],[71.56,100,1],[46.34,100,1],[46.34,100,9]],\"w\":0,\"h\":0}],\"w\":71.56,\"h\":100,\"x\":0,\"y\":0}",
 *       "thumb":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U8/2016/04/12/111736242_9195288177579642/0.jpg",
 *       "create_time":"2016/04/01 12:11:17"
 *     }],
 *     "pageCount":32,
 *     "pageNum":0,
 *     "pageSize":9
 *
 *   },
 *   "success": 1
 * }
 * 测试地址：http://127.0.0.1:3000/design/getDefaulGraphList?user_id=1&pageNum=0&pageSize=3
 *          http://127.0.0.1:3000/design/getDefaulGraphList?user_id=1&pageNum=0&pageSize=3&key=%E6%96%87%E6%9C%AC
 *
 * */
function getDefaulGraphList(req, res, next) {
    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var type = req.query.type || req.body.type ||null;
    var key = req.query.key || req.body.key ||null;
    var pageNum = Number(req.query.pageNum || req.body.pageNum ||0);
    var pageSize = Number(req.query.pageSize || req.body.pageSize ||12);
    var skipCnt = pageNum*pageSize;

    var user_id = req.query.user_id || req.body.user_id ||0;
    if(!user_id){
        return ret_func(0,'fail! user_id is null!',null);
    }
    var entity=null;
    if(type==null){
        entity = new ItbGraphModel({
            del_flg:0
        });
    }else{
        entity = new ItbGraphModel({
            graph_type:type,
            del_flg:0
        });
    }


    // 无关键字
    if(key==null){
        entity.findCountFromDB(function(error,itemCount){
            if(error){
                console.log(error);
                return ret_func(0,error,null);
            }
            entity.findFromDB(function(error2,items){
                if(error2){
                    console.log(error2);
                    return ret_func(0,error2,null);
                }

                var data = {};
                data.pageCount = Math.ceil(Number(itemCount||'0')/pageSize);// 向上取整
                data.pageNum = pageNum;
                data.pageSize = pageSize;
                data.graphList = items;

                return ret_func(1,'success',data);
            },skipCnt,pageSize);
        });
    }else{
        // 有关键字
        entity.findCountFromDBWithKey(key, function(error,itemCount){
            if(error){
                console.log(error);
                return ret_func(0,error,null);
            }

            entity.findFromDBWithKey(key, function(error2,items){
                if(error2){
                    console.log(error2);
                    return ret_func(0,error2,null);
                }

                var data = {};
                data.pageCount = Math.ceil(Number(itemCount||'0')/pageSize);// 向上取整
                data.pageNum = pageNum;
                data.pageSize = pageSize;
                data.graphList = items;

                var retJson ={
                    success: 1,
                    msg: 'success',
                    data:data
                };

                return ret_func(1,'success',data);
            },skipCnt,pageSize);
        });
    }

}
router.get('/getDefaulGraphList', getDefaulGraphList);
router.post('/getDefaulGraphList', getDefaulGraphList);

//------------------------------------------------------------------
/* 保存图片到DB.
 * 方式:GET/POST
 * 参数:img_name:图片名称
 * 参数:user_type:用户类型
 * 参数:user_id:用户id
 * 参数:url:图片地址
 * 返回:新的url
 *
 * */
function saveImageToDB(req, res, next) {
    //数据从以下请求获得：
    var img_name = req.query.img_name || req.body.img_name;
    var user_type = req.query.user_type || req.body.user_type;
    var user_id = req.query.user_id || req.body.user_id;
    var url = req.query.url || req.body.url;


    saveImageToDBCore(img_name, user_type, user_id, url, function(error, insertId){
        return res.json({success:1, msg:'',data:{insertId:insertId}});
    });

}
// 保存数据到Itb_image中
function saveImageToDBCore(img_name, user_type, user_id, url,callback){
    var entity = new ItbImageModel({
        user_type:user_type,
        user_id:user_id,
        img_name:img_name,
        url:url,
        update_by:user_id,
    });
    entity.saveToDB(function(error,insertId){
        console.log('upload:saveToDB:'+insertId);
        callback(error, insertId);
    });
}
router.get('/saveImageToDB', saveImageToDB);
router.post('/saveImageToDB', saveImageToDB);


//------------------------------------------------------------------

/* 保存音视频到DB.
 * 方式:GET/POST
 * 参数:media_name:图片名称
 * 参数:user_type:用户类型
 * 参数:media_type:媒体类型
 * 参数:user_id:用户id
 * 参数:url:媒体地址
 * 返回:新的url
 *
 * */
function saveMediaToDB(req, res, next) {
    //数据从以下请求获得：
    var media_name = req.query.media_name || req.body.media_name;
    var user_type = req.query.user_type || req.body.user_type;
    var media_type = req.query.media_type || req.body.media_type;
    var user_id = req.query.user_id || req.body.user_id;
    var url = req.query.url || req.body.url;

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    if(!media_name ||!user_type||!media_type||!user_id||!url){
        return ret_func(0,'参数错误',{});
    }
    if(media_type!=10&&media_type!=20){
        return ret_func(0,'媒体类型标识无效',{});
    }

    saveMediaToDBCore(media_name, user_type,media_type, user_id, url, function(error, insertId){
        return ret_func(1,'成功',{insertId:insertId});
    });

}
// 保存数据到Itb_media中
function saveMediaToDBCore(media_name, user_type,media_type, user_id, url,callback){
    var entity = new ItbMediaModel({
        user_type:user_type,
        media_type:media_type,
        user_id:user_id,
        media_name:media_name,
        url:url,
        update_by:user_id,
    });
    entity.saveToDB(function(error,insertId){
        console.log('upload:saveToDB:'+insertId);
        callback(error, insertId);
    });
}
router.get('/saveMediaToDB', saveMediaToDB);
router.post('/saveMediaToDB', saveMediaToDB);
//------------------------------------------------------------------

/**
 * 保存视频设计文档信息
 * @param req
 * @param res
 * @param next
 * @returns {*}
 */
function saveVideoDesignInfo(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // get parameter
    var device = req.body.device || req.query.device;
    var uuid = req.body.uuid || req.query.uuid;

    var userId = Number(req.body.uId || req.query.uId || '0')||0;
    var ver = Number(req.body.ver || req.query.ver || '1')||1;
    var duration = Number(req.body.dur || req.query.dur || '0')||0;// 必须
    var designId = Number(req.body.dId || req.query.dId || '0')||0;
    var designName = req.body.dNm || req.query.dNm || '视频模版';

    var sizeId = Number(req.body.sizeId || req.query.sizeId || '0')||0;
    var typeId = Number(req.body.typeId || req.query.typeId || '0')||0;

    var tgData = req.body.tgData || req.query.tgData || '';// 必须
    var vData = req.body.vData || req.query.vData || '';// 必须
    var caIds = req.body.caIds || req.query.caIds || '';//
    var themeThumb = req.body.themeThumb || req.query.themeThumb || '';//

    //var editDataStr = req.body.editData || req.query.editData || '{}';
    //var editData = JSON.parse(editDataStr);

    // Return Function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    // 参数检查
    if(userId<=0) {
        return ret_func(0, "非法用户");
    }
    if(tgData.length==0 || vData.length==0) {
        return ret_func(0, "文档数据错误");
    }

    // 检索user
    var userEnt = new ItbUserModel({
        user_id : userId,
        del_flg : 0
    });
    userEnt.findFromDB(function(userChkErr, userInfoRet){
        if (userChkErr){
            console.log('design.js [saveVideoDesignInfo] Check User Err: '+userChkErr);
            return ret_func(0,CODE.OPERATION_FAILED);
        }

        // 合法用户
        if(userInfoRet && userInfoRet.length>0) {
            var userInfo = userInfoRet[0];

            if (designId<=0) {// 新建设计模版

                var newDocEnt = new VideoDesignDocModel({
                    design_name: designName,
                    user_id: userId,
                    user_type: userInfo.user_type||1,
                    state: 10,// 制作中
                    publish: 0,// 未发布
                    vip: 0,// 普通模版
                    tg_data: tgData||'',
                    v_data: vData||'',
                    cust_ani_ids: caIds||'',
                    duration: duration,
                    size_id: sizeId,
                    type_id: typeId,
                    theme_thumb: themeThumb||'',
                    ver: ver,
                    update_by: userId,
                });
                newDocEnt.saveToDB(function(saveErr, newDocId){
                    if (saveErr) {
                        console.log('design.js [saveVideoDesignInfo] Insert Doc Err: '+saveErr);
                        return ret_func(0,CODE.OPERATION_FAILED);
                    }

                    // 查找统一项目表
                    var uniEnt = new YjxUniItemsModel({
                        item_type: 30,// 视频模版
                        item_id: newDocId,
                        del_flg: 0
                    });
                    uniEnt.findFromDB(function(getErr, getRet) {
                        if (getErr) {
                            console.log('design.js [saveVideoDesignInfo] Find UniItem Err: '+getErr);
                        }

                        var uniItemId = 0;
                        if(getRet && getRet.length>0) {
                            uniItemId = getRet[0].uni_item_id||0;
                        }
                        return ret_func(1,CODE.OPERATION_SUCCESS,{designId:newDocId, uniItemId:uniItemId});
                    });
                });

            } else {// 更新设计模版
                // 先检查设计模版
                var chkEnt = new VideoDesignDocModel({
                    design_id: designId,
                    del_flg: 0,
                });
                chkEnt.findFromDB(function(chkErr, chkRet){
                    if (chkErr) {
                        console.log('design.js [saveVideoDesignInfo] Find Doc Err: '+chkErr);
                        return ret_func(0,CODE.OPERATION_FAILED);
                    }

                    if(chkRet && chkRet.length>0) {
                        var designInfo = chkRet[0];

                        if(Number(designInfo.publish || '0') == 1) {
                            return ret_func(0,"不能修改已发布的设计模版");
                        }

                        // 更新doc
                        var docEnt = new VideoDesignDocModel({
                            design_id: designId,
                            design_name: designName,
                            //user_id 不更新
                            tg_data: tgData||'',
                            v_data: vData||'',
                            cust_ani_ids: caIds||'',
                            duration: duration,
                            theme_thumb: themeThumb||'',
                            //size_id: sizeId,
                            //type_id: typeId,
                            ver: ver,
                            update_by: userId,
                        });
                        docEnt.updateToDB(function(updErr, updRet){
                            if (updErr) {
                                console.log('design.js [saveVideoDesignInfo] Update Doc Err: '+updErr);
                                return ret_func(0,CODE.OPERATION_FAILED);
                            }

                            // 查找统一项目表
                            var uniEnt = new YjxUniItemsModel({
                                item_type: 30,// 视频模版
                                item_id: designId,
                                del_flg: 0
                            });
                            uniEnt.findFromDB(function(getErr, getRet) {
                                if (getErr) {
                                    console.log('design.js [saveVideoDesignInfo] Find UniItem Err: '+getErr);
                                }

                                var uniItemId = 0;
                                if(getRet && getRet.length>0) {
                                    uniItemId = getRet[0].uni_item_id||0;
                                }
                                return ret_func(1,CODE.OPERATION_SUCCESS,{designId:designId, uniItemId:uniItemId});
                            });
                        });

                    } else {
                        return ret_func(0,"设计模版不存在");
                    }
                });
            }

        } else {
            return ret_func(0,"非法用户");
        }
    });

}
router.get('/saveVideoDesignInfo', saveVideoDesignInfo);
router.post('/saveVideoDesignInfo', saveVideoDesignInfo);
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取音频/视频列表 (设计编辑器用 编辑)
 * 方式:GET/POST
 * 参数 device:
 * 参数 userId: 用户id
 * 参数 type: 10音频, 20视频, 30音视频混查
 * 参数 pageNum: 分页号, 当前第几页, >=0
 * 参数 pageSize: 分页大小, 一页的数量
 * 参数[可选] key: 搜索关键字
 * 返回数据:
 * {
 *   "msg": "成功",
 *   "data": {
 *     "mediaList":[{
 *       "media_id": 36,
 *       "media_name": "企业培训",
 *       "media_type": 10,
 *       "url":"xxx.acc",
 *       "thumbs":"http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U8/2016/04/12/111736242_9195288177579642/0.jpg",
 *       "create_time": "2016/04/01 12:11:17"
 *     }],
 *     "pageCount":32,
 *     "pageNum":0,
 *     "pageSize":9
 *   },
 *   "success": 1
 * }
 *
 * */
function getMediaList(req, res, next) {
    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var key = req.query.key || req.body.key || null;
    var type = Number(req.query.type || req.body.type ||'0')||0;
    var pageNum = Number(req.query.pageNum || req.body.pageNum ||'0')||0;
    var pageSize = Number(req.query.pageSize || req.body.pageSize ||'12')||12;
    var skipCnt = pageNum*pageSize;

    var userId = req.query.userId || req.body.userId || 0;

    var entity = new ItbMediaModel();
    entity.findCountFromDBWithKey(userId, key, type, function(error,pageCount){
        if(error){
            console.log(error);
            return ret_func(0,error,null);
        }

        entity.findFromDBWithKey(userId, key, type, pageNum, pageSize, function(error2,items){
            if(error2){
                console.log(error2);
                return ret_func(0,error2,null);
            }

            var data = {};
            data.pageCount = Math.ceil(Number(pageCount||'0')/pageSize);// 向上取整
            data.pageNum = pageNum;
            data.pageSize = pageSize;
            data.mediaList = items;

            var retJson ={
                success: 1,
                msg: 'success',
                data:data
            };

            return ret_func(1,'success',data);
        });
    });
};
router.get('/getMediaList', getMediaList);
router.post('/getMediaList', getMediaList);

//------------------------------------------------------------------
/* 删除音视频 (设计编辑器用 编辑)
 * 方式:GET/POST
 * 参数 device:
 * 参数 userId: 用户id
 * 参数 mediaId: 媒体id
 * 返回数据:
 * {
 *   "msg": "成功",
 *   "data": {},
 *   "success": 1
 * }
 *
 * */
function deleteMedia(req, res, next) {
    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var mediaId = Number(req.query.mediaId || req.body.mediaId ||'0')||0;
    var userId = Number(req.query.userId || req.body.userId || '0')||0;

    if(!mediaId || !userId){
        return ret_func(0,'参数错误',null);
    }

    (new ItbMediaModel).logicDeleteMediaByUser(userId, mediaId, function(error){
        if(error){
            console.log(error);
            return ret_func(0,error,null);
        }
        return ret_func(1,'success',{});
    });
};
router.get('/deleteMedia', deleteMedia);
router.post('/deleteMedia', deleteMedia);

//------------------------------------------------------------------
/* 获取自定义动画列表 (设计编辑器用 编辑)
 * 方式:GET/POST
 * 参数 device:
 * 参数 userId[可选]: 用户id (null或0时,只返回共通动画, 大于0时返回共通+私有的动画)
 * 参数 sizeId: 匹配尺寸
 * 参数 pageNum:
 * 参数 pageSize:
 * 返回数据:
 * {
 *   "msg": "成功",
 *   "data": {},
 *   "success": 1
 * }
 *
 * */
function getCustAnimations(req, res, next) {
    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var userId = Number(req.query.userId || req.body.userId || '0')||0;
    var sizeId = Number(req.query.sizeId || req.body.sizeId || '0')||0;
    var pageNum = Number(req.query.pageNum || req.body.pageNum ||'0')||0;
    var pageSize = Number(req.query.pageSize || req.body.pageSize ||'12')||12;
    var use = Number(req.query.use || req.body.use ||'0')||0;

    if(!sizeId){
        return ret_func(0,'参数错误',null);
    }

    var ent = new YjxCustAnimationModel();
    ent.getCustAniListBySizeCnt(userId, 10, sizeId, use, function(err, tCnt) {
        if(err) {
            console.log(err);
            return ret_func(0,err,null);
        }

        var data = {
            totalCnt: tCnt,
            pageCnt: Math.ceil(Number(tCnt||'0')/pageSize),// 向上取整
            pageNum: pageNum,
            pageSize: pageSize,
            aniList: []
        };

        if(tCnt>0) {
            ent.getCustAniListBySize(userId, 10, sizeId, use, pageNum, pageSize,function(err2, items){
                if(err2) {
                    console.log(err2);
                    return ret_func(0,err2,null);
                }

                if(items && items.length>0) {
                    for(var i=0;i<items.length;i++) {
                        var item=items[i];

                        var info = {
                            ct: 1291,//GCJ_CLASS_TYPE.CLASS_TYPE_VIDEO_ANIMATION_PARAM_AE
                            dbId: item.ani_id||0,
                            use: item.use||0,
                            private: Number(item.private||'0')||0,
                            title: item.ani_name||'自定义动画',
                            duration: 0,// TODO
                            start: 0,
                            video: item.url||item.thumb_v||'',
                            tmpl_set: {},
                            tmpl_para: {}
                        };

                        // 模版默认时长
                        var AE_BODYMOVIN_TMPL_SET_KEY_DEFAULT_DURATION=1;
                        // 模版默认支持的可修改文字的个数
                        var AE_BODYMOVIN_TMPL_SET_KEY_REPLACE_TEXT_COUNT=2;
                        // 模版默认支持的可修改图片的个数
                        var AE_BODYMOVIN_TMPL_SET_KEY_REPLACE_IMAGE_COUNT=3;

                        var tmplSet = JSON.parse(item.tmpl_set||'{}')||{};
                        if(tmplSet && tmplSet.hasOwnProperty(AE_BODYMOVIN_TMPL_SET_KEY_DEFAULT_DURATION)) {// 默认时长
                            info.duration = Number(tmplSet[AE_BODYMOVIN_TMPL_SET_KEY_DEFAULT_DURATION]||'0')||0;
                            info.tmpl_set=tmplSet;
                        }

                        var tmplPara = JSON.parse(item.tmpl_para||'{}')||{};
                        if(tmplPara) {
                            info.tmpl_para=tmplPara;
                        }

                        data.aniList.push(info);
                    }
                }

                return ret_func(1,'success',data);
            });
        } else {
            return ret_func(1,'success',data);
        }
    });
};
router.get('/getCustAnimations', getCustAnimations);
router.post('/getCustAnimations', getCustAnimations);

//------------------------------------------------------------------
/* 删除自定义动画
 * 方式:GET/POST
 * 参数 device:
 * 参数 userId: 用户id
 * 参数 aniId: 动画id
 * 返回数据:
 * {
 *   "msg": "成功",
 *   "data": {},
 *   "success": 1
 * }
 *
 * */
function delCustAnimation(req, res, next) {
    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var aniId = Number(req.query.aniId || req.body.aniId ||'0')||0;
    var userId = Number(req.query.userId || req.body.userId || '0')||0;

    if(!aniId || !userId){
        return ret_func(0,'参数错误',null);
    }

    (new YjxCustAnimationModel).logicDelCustAniByUser(userId, aniId, function(error){
        if(error){
            console.log(error);
            return ret_func(0,error,null);
        }
        return ret_func(1,'success',{});
    });
};
router.get('/delCustAnimation', delCustAnimation);
router.post('/delCustAnimation', delCustAnimation);

//------------------------------------------------------------------
/**
 * 保存(私有)自定义动画
 * @returns {*}
 */
function saveCustAnimation(req, res, next) {
    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var aniType = Number(req.query.aniType || req.body.aniType || '0')||0;
    var userType = Number(req.query.userType || req.body.userType || '0')||0;
    var userId = Number(req.query.userId || req.body.userId || '0')||0;
    var sizeId = Number(req.query.sizeId || req.body.sizeId || '0')||0;
    var aniName = req.query.aniName || req.body.aniName || '自定义动画';
    var tmplJson = req.query.tmplJson || req.body.tmplJson || '';
    var tmplSet = req.query.tmplSet || req.body.tmplSet || '';
    var tmplPara = req.query.tmplPara || req.body.tmplPara || '';
    var dur = Number(req.query.dur || req.body.dur || '0')||0;
    var url = req.query.vUrl || req.body.vUrl || '';
    var thumb_v = req.query.vThumbUrl || req.body.vThumbUrl || '';
    var thumbs = req.query.thumbs || req.body.thumbs || '';
    var use = Number(req.query.use || req.body.use || '10')||10;// 用途：10视频模版用, 20转场效果用

    if(!sizeId || !userId){
        return ret_func(0,'参数错误',null);
    }

    var entity = new YjxCustAnimationModel({
        ani_type: aniType,
        use: use,
        private: 1,// 私有
        user_type: userType,
        user_id: userId,
        ani_name: aniName,
        tmpl_json: tmplJson,
        tmpl_set: tmplSet,
        tmpl_para: tmplPara,
        url: url,
        thumb_v: thumb_v,
        thumbs: thumbs,
        size_id: sizeId,
        duration: dur,
        update_by:userId,
    });
    entity.saveToDB(function(error,insertId){
        console.log('YjxCustAnimationModel:saveToDB:'+insertId);
        if(error){
            console.log(error);
            return ret_func(0,error,null);
        }
        return ret_func(1,'success',{ani_id:insertId});
    });
};
router.get('/saveCustAnimation', saveCustAnimation);
router.post('/saveCustAnimation', saveCustAnimation);


//------------------------------------------------------------------
/**
 * 生成视频模版场景页图
 * @returns {*}
 */
function createVideoScenesImages(req, res, next) {
    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var designId = Number(req.query.designId || req.body.designId || '0')||0;

    if(!designId){
        return ret_func(0,'参数错误',null);
    }

    rpcFunc.createVideoScenesImages(designId, function(err, ret){
        if(err) {
            return ret_func(0,err,null);
        }
        return ret_func(1,'success',ret);
    });
};
router.get('/createVideoScenesImages', createVideoScenesImages);
router.post('/createVideoScenesImages', createVideoScenesImages);

//------------------------------------------------------------------
/**
 * 一键秀排版视频模板文档
 * @param designId  设计视频 id
 * @param withWm    是否携带水印
 * @returns {*}
 */
function createVideoDesignDocVideo(req, res, next) {
    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var designId = Number(req.query.designId || req.body.designId || '0')||0;
    var withWm = Number(req.query.withWm || req.body.withWm || '0')||0;// 1:带水印

    if(!designId){
        return ret_func(0,'参数错误',null);
    }

    rpcFunc.yjxCreateVideoDesignDocVideo(designId, withWm, function(err, ret){
        if(err) {
            return ret_func(0,err,null);
        }
        return ret_func(1,'success',ret);
    });
};
router.get('/createVideoDesignDocVideo', createVideoDesignDocVideo);
router.post('/createVideoDesignDocVideo', createVideoDesignDocVideo);

//------------------------------------------------------------------
/**
 * 根据bodymovin的json文件生成视频
 * 用于设计师设计上传AE文件后，生成mp4预览视频
 * 参数：userId
 * 参数：lt_data:     Lottie文档json数据, 必需存在
 * 参数：lt_ver:      ［保留］版本号
 * 参数：w:            宽
 * 参数：h:            高
 * 参数：daudio:      ［保留］默认音频的路径（必需为aac格式）
 * 参数：thumb_video_frames: [可选]生成预览视频的帧的数组的json，例如 "[1,4,9]"
 * 参数：thumb_image_frame:  [可选]生成预览图的帧，例如，3
 * 参数：rate_num:  帧率的分子，例如 10
 * 参数：rate_den:  帧率的分母，例如 1
 *
 * callback: {video:'完整视频.mp4', thumb:'预览视频.mp4', preview:'预览图.jpg'}
 */
function createVideoForAEJson(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var userId = Number(req.query.userId || req.body.userId || '0')||0;
    var ltData = req.query.ltData || req.body.ltData || '';
    var ltVer = req.query.ltVer || req.body.ltVer || 0;
    var w = Number(req.query.w || req.body.w || '300')||300;
    var h = Number(req.query.h || req.body.h || '300')||300;
    var daudio = req.query.daudio || req.body.daudio || '';
    var thumbVideoFrames = req.query.thumbVideoFrames || req.body.thumbVideoFrames || '[1,2,3]';
    var thumbImageFrame = Number(req.query.thumbImageFrame || req.body.thumbImageFrame || '0')||1;
    var rateNum = Number(req.query.rateNum || req.body.rateNum || '10')||10;
    var rateDen = Number(req.query.rateDen || req.body.rateDen || '1')||1;

    if(!ltData && ltData.length==0) {
        return ret_func(0,'参数错误',null);
    }

    rpcFunc.createVideoForAEJson(userId, ltData, ltVer, w, h, daudio,
        thumbVideoFrames, thumbImageFrame, rateNum, rateDen,
        function(err, ret){
            if(err) {
                return ret_func(0,err,null);
            }
            return ret_func(1,'success',ret);
    });
};
router.get('/createVideoForAEJson', createVideoForAEJson);
router.post('/createVideoForAEJson', createVideoForAEJson);

//------------------------------------------------------------------
/**
 * 从bodymovin的json文件解析出数据
 * 用于设计师设计上传AE文件后，解析数据，方便在编辑器中使用
 * 参数：userId
 * 参数：lt_data：   Lottie文档json数据, 必需存在
 * 参数：lt_ver：    ［保留］版本号
 * 参数：w:          宽
 * 参数：h:          高
 * 参数：rate_num：  帧率的分子，例如 10
 * 参数：rate_den：  帧率的分母，例如 1
 *
 */
function parseInfoFromAEJson(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    var userId = Number(req.query.userId || req.body.userId || '0')||0;
    var ltData = req.query.ltData || req.body.ltData || '';
    var ltVer = req.query.ltVer || req.body.ltVer || 0;
    var w = Number(req.query.w || req.body.w || '300')||300;
    var h = Number(req.query.h || req.body.h || '300')||300;
    var rateNum = Number(req.query.rateNum || req.body.rateNum || '10')||10;
    var rateDen = Number(req.query.rateDen || req.body.rateDen || '1')||1;

    if(!ltData && ltData.length==0) {
        return ret_func(0,'参数错误',null);
    }

    rpcFunc.parseInfoFromAEJson(userId, ltData, ltVer, w, h, rateNum, rateDen,
        function(err, ret){
            if(err) {
                return ret_func(0,err,null);
            }
            return ret_func(1,'success',ret);
        });
};
router.get('/parseInfoFromAEJson', parseInfoFromAEJson);
router.post('/parseInfoFromAEJson', parseInfoFromAEJson);


/**
 *  获取未发布模板的核心数据结构
 *
 *  @author 王俊
 *  @date 2017-12-27
 *
 *  参数: designId    模板子表 id
 *  参数: itemType     与 yjx_uni_items 中的 item_type 一致, 10:单页, 20:PPT, 30:视频',
 *
 *  测试地址: http://localhost:3000/design/getTmplDocInfo_for_debug?designId=66&itemType=30
 */
function getTmplDocInfo_for_debug(req, res, next) {
    var designId = retUtil.numberFromReq(req, 'designId');
    var itemType = retUtil.numberFromReq(req, 'itemType');

    documentUtil.getTmplDocInfo_for_debug(designId, itemType, function (getTmplErr, data) {
        if(getTmplErr) {
            console.log('yjx/v1/document.js [getTmplDocInfo_for_debug] getTmplErr: ' + getTmplErr);
            return retUtil.ret_err_json(getTmplErr, res);
        }
        data.docId = 0;
        data.docString = JSON.stringify(data.docString || {});
        return retUtil.ret_succ_json(data, res);
    });
}
router.get('/getTmplDocInfo_for_debug', getTmplDocInfo_for_debug);
router.post('/getTmplDocInfo_for_debug', getTmplDocInfo_for_debug);

/**
 *  根据模板核心数据结构创建作品
 *
 *  @author 王俊
 *  @date 2017-12-28
 *
 *  参数: tmplId    统一模板 id
 *  参数: userId    用户唯一标识
 *  参数: docString 模板核心数据
 *
 *  测试地址: http://localhost:3000/design/getTmplDocInfo_for_debug?designId=66&itemType=30
 */
function newUserDoc_for_debug(req, res, next) {
    var tmplId = retUtil.numberFromReq(req, 'tmplId');
    var userId = retUtil.numberFromReq(req, 'userId');
    var docString = retUtil.stringFromReq(req, 'docString');

    if(tmplId <= 0 || userId <= 0 || !docString || docString.length <2) {
        return retUtil.ret_err_json('参数错误', res);
    }

    documentUtil.newUserDoc_v1_0_for_debug(userId, tmplId, docString, function (error, data) {
        if (error) {
            console.log('yjx/v1/document.js [newUserDoc_for_debug] err: ' + error);
            return retUtil.ret_err_json(error, res);
        }
        return retUtil.ret_succ_json(data, res);
    });
}
router.get('/newUserDoc_for_debug', newUserDoc_for_debug);
router.post('/newUserDoc_for_debug', newUserDoc_for_debug);



/**
 *  根据模版id获取作品预览
 *
 *  @author 李强
 *  @date 2017-12-28
 *
 *  参数: docId    用户作品唯一标识
 *  参数: userId    用户唯一标识
 *
 *  测试地址: http://localhost:3000/design/getDocPreview_for_debug?userId=1&docId=100
 */

function getDocPreview_for_debug(req, res, next) {
    var docId = retUtil.numberFromReq(req, 'docId');
    var userId = retUtil.numberFromReq(req, 'userId');

    if(docId <= 0 || userId <= 0) {
        return retUtil.ret_err_json('参数错误', res);
    }

    documentUtil.getDocPreview_for_debug(userId, docId,function (error, data) {
        if (error) {
            console.log('design.js [getDocPreview_for_debug] err: ' + error);
            return retUtil.ret_err_json(error, res);
        }
        return retUtil.ret_succ_json(data, res);
    });
}
router.get('/getDocPreview_for_debug', getDocPreview_for_debug);
router.post('/getDocPreview_for_debug', getDocPreview_for_debug);

//------------------------------------------------------------------
module.exports = router;
